<template>
  <div class="product-detail-page">
    <HeaderNav />
    
    <div class="container" v-loading="loading">
      <!-- 面包屑 -->
      <el-breadcrumb separator="/" class="breadcrumb">
        <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item v-if="productDetail.categoryName">{{ productDetail.categoryName }}</el-breadcrumb-item>
        <el-breadcrumb-item>商品详情</el-breadcrumb-item>
      </el-breadcrumb>

      <div class="product-main" v-if="productDetail.id">
        <!-- 左侧：图片轮播 -->
        <div class="product-images">
          <el-carousel :interval="0" indicator-position="outside" height="500px">
            <el-carousel-item v-for="(image, index) in imageList" :key="index">
              <img :src="image" :alt="productDetail.productName" />
            </el-carousel-item>
          </el-carousel>
        </div>

        <!-- 右侧：商品信息 -->
        <div class="product-info">
          <h1 class="product-name">{{ productDetail.productName }}</h1>
          <div class="product-meta">
            <span class="sales">已售{{ productDetail.salesCount || 0 }}件</span>
            <span class="views">浏览量{{ productDetail.viewCount || 0 }}</span>
          </div>
          
          <div class="price-section">
            <span class="current-price">¥{{ formatPrice(productDetail.price) }}</span>
            <span v-if="productDetail.originalPrice" class="original-price">
              ¥{{ formatPrice(productDetail.originalPrice) }}
            </span>
            <span v-if="productDetail.discountPercentage" class="discount">
              立省{{ productDetail.discountPercentage }}%
            </span>
          </div>

          <div class="stock-info">
            <span>库存：</span>
            <span :class="{ 'low-stock': productDetail.stockQuantity < 10 }">
              {{ productDetail.stockQuantity || 0 }}件
            </span>
          </div>

          <div class="actions">
            <el-button 
              type="danger" 
              size="large" 
              @click="handleAddToCart"
              :loading="addingToCart"
            >
              加入购物车
            </el-button>
            <el-button 
              type="primary" 
              size="large" 
              @click="handleBuyNow"
              :loading="buyingNow"
            >
              立即购买
            </el-button>
            <el-button
              size="large"
              :class="{ 'is-favorite': productDetail.isFavorited }"
              :loading="favoriteLoading"
              @click="toggleFavoriteStatus"
            >
              <el-icon v-if="!favoriteLoading"><Star /></el-icon>
              {{ productDetail.isFavorited ? '已收藏' : '收藏' }}
            </el-button>
          </div>
        </div>
      </div>

      <!-- 商品详情 -->
      <div class="product-detail-section">
        <el-tabs v-model="activeTab">
          <el-tab-pane label="商品详情" name="detail">
            <div class="detail-content" v-html="productDetail.description"></div>
          </el-tab-pane>
          
          <el-tab-pane label="商品评价" name="reviews">
            <div class="reviews-section">
              <div class="review-stats" v-if="reviewStats.total > 0">
                <div class="avg-rating">
                  <span class="rating-value">{{ reviewStats.averageRating.toFixed(1) }}</span>
                  <el-rate v-model="reviewStats.averageRating" disabled show-score />
                </div>
                <div class="rating-distribution">
                  <div v-for="i in 5" :key="i" class="rating-bar">
                    <span>{{ 6 - i }}星</span>
                    <el-progress :percentage="(reviewStats.ratingCount[6-i] / reviewStats.total * 100) || 0" />
                  </div>
                </div>
              </div>

              <div class="review-list" v-loading="reviewsLoading">
                <div v-for="review in reviews" :key="review.id" class="review-item">
                  <div class="review-header">
                    <el-avatar :src="review.avatar" :size="40">{{ review.realName?.[0] || 'U' }}</el-avatar>
                    <div class="review-user-info">
                      <div class="username">{{ review.realName || review.username }}</div>
                      <el-rate v-model="review.rating" disabled size="small" />
                      <span class="review-time">{{ review.createTime }}</span>
                    </div>
                  </div>
                  <div class="review-content">{{ review.content }}</div>
                  <div v-if="review.images && review.images.length > 0" class="review-images">
                    <img v-for="(img, idx) in review.images" :key="idx" :src="img" @click="previewImage(img)" />
                  </div>
                </div>
                <el-empty v-if="!reviewsLoading && reviews.length === 0" description="暂无评价" />
              </div>

              <!-- 分页 -->
              <el-pagination
                v-if="reviewTotal > 0"
                v-model:current-page="reviewPagination.current"
                v-model:page-size="reviewPagination.size"
                :total="reviewTotal"
                layout="prev, pager, next"
                @current-change="loadReviews"
                class="review-pagination"
              />
            </div>
          </el-tab-pane>
        </el-tabs>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { Star } from '@element-plus/icons-vue'
import HeaderNav from '@/components/HeaderNav.vue'
import { getProductDetail } from '@/api/product'
import { toggleFavorite, checkFavorite } from '@/api/favorite'
import { getReviewsByProductId, getAverageRating, countReviews } from '@/api/review'
import { addToCart, updateSelectedStatus } from '@/api/cart'
import { getImageUrl } from '@/utils/image'

const route = useRoute()
const router = useRouter()
const loading = ref(false)
const activeTab = ref('detail')
const productDetail = ref({})
const imageList = ref([])
const reviews = ref([])
const reviewsLoading = ref(false)
const reviewTotal = ref(0)
const favoriteLoading = ref(false)
const addingToCart = ref(false)
const buyingNow = ref(false)
const reviewStats = reactive({
  total: 0,
  averageRating: 0,
  ratingCount: { 1: 0, 2: 0, 3: 0, 4: 0, 5: 0 }
})

const reviewPagination = reactive({
  current: 1,
  size: 10
})

// 格式化价格
const formatPrice = (price) => {
  if (!price) return '0.00'
  return Number(price).toFixed(2)
}

// 加载商品详情
const loadProductDetail = async () => {
  loading.value = true
  try {
    const res = await getProductDetail(route.params.id)
    if (res.code === 200 && res.data) {
      productDetail.value = res.data
      // 构建图片列表（使用统一的URL处理）
      imageList.value = []
      if (res.data.mainImage) {
        imageList.value.push(getImageUrl(res.data.mainImage))
      }
      if (res.data.imageList && res.data.imageList.length > 0) {
        imageList.value.push(...res.data.imageList.map(img => getImageUrl(img)))
      }
      // 如果没有图片，会显示占位图（在组件模板中处理）
    } else {
      ElMessage.error(res.message || '加载商品详情失败')
    }
  } catch (error) {
    console.error('加载商品详情失败:', error)
    ElMessage.error('加载商品详情失败')
  } finally {
    loading.value = false
  }
}

// 切换收藏
const toggleFavoriteStatus = async () => {
  if (!productDetail.value?.id) {
    ElMessage.warning('商品信息不完整')
    return
  }
  
  favoriteLoading.value = true
  try {
    const res = await toggleFavorite(productDetail.value.id)
    if (res.code === 200) {
      productDetail.value.isFavorited = res.data
      ElMessage.success(res.data ? '收藏成功' : '取消收藏成功')
    } else {
      ElMessage.error(res.message || '操作失败')
    }
  } catch (error) {
    console.error('切换收藏失败:', error)
    ElMessage.error('操作失败，请稍后重试')
  } finally {
    favoriteLoading.value = false
  }
}

// 检查收藏状态
const checkFavoriteStatus = async () => {
  try {
    const res = await checkFavorite(productDetail.value.id)
    if (res.code === 200) {
      productDetail.value.isFavorited = res.data
    }
  } catch (error) {
    console.error('检查收藏状态失败:', error)
  }
}

// 加入购物车
const handleAddToCart = async () => {
  if (!productDetail.value?.id) {
    ElMessage.warning('商品信息不完整')
    return
  }
  
  // 检查库存
  if (!productDetail.value.stockQuantity || productDetail.value.stockQuantity <= 0) {
    ElMessage.warning('商品库存不足')
    return
  }
  
  addingToCart.value = true
  try {
    const res = await addToCart(productDetail.value.id, 1)
    if (res.code === 200) {
      ElMessage.success('已添加到购物车')
    } else {
      ElMessage.error(res.message || '添加失败')
    }
  } catch (error) {
    console.error('加入购物车失败:', error)
    ElMessage.error('添加失败，请稍后重试')
  } finally {
    addingToCart.value = false
  }
}

// 立即购买
const handleBuyNow = async () => {
  if (!productDetail.value?.id) {
    ElMessage.warning('商品信息不完整')
    return
  }
  
  // 检查库存
  if (!productDetail.value.stockQuantity || productDetail.value.stockQuantity <= 0) {
    ElMessage.warning('商品库存不足')
    return
  }
  
  buyingNow.value = true
  try {
    // 1. 先将商品添加到购物车
    const addRes = await addToCart(productDetail.value.id, 1)
    if (addRes.code !== 200) {
      ElMessage.error(addRes.message || '添加到购物车失败')
      return
    }
    
    // 2. 设置该商品为选中状态
    const selectRes = await updateSelectedStatus(productDetail.value.id, true)
    if (selectRes.code !== 200) {
      ElMessage.error('选中商品失败')
      return
    }
    
    // 3. 跳转到结算页面
    router.push('/order/checkout')
  } catch (error) {
    console.error('立即购买失败:', error)
    ElMessage.error('操作失败，请稍后重试')
  } finally {
    buyingNow.value = false
  }
}

// 加载评价
const loadReviews = async () => {
  if (!productDetail.value.id) return
  
  reviewsLoading.value = true
  try {
    const res = await getReviewsByProductId(productDetail.value.id, {
      status: 1,
      limit: reviewPagination.size
    })
    if (res.code === 200 && res.data) {
      reviews.value = res.data
    }
  } catch (error) {
    console.error('加载评价失败:', error)
  } finally {
    reviewsLoading.value = false
  }
}

// 加载评价统计
const loadReviewStats = async () => {
  if (!productDetail.value.id) return
  
  try {
    const [avgRes, countRes] = await Promise.all([
      getAverageRating(productDetail.value.id, { status: 1 }),
      countReviews(productDetail.value.id, { status: 1 })
    ])
    
    if (avgRes.code === 200) {
      reviewStats.averageRating = avgRes.data || 0
    }
    if (countRes.code === 200) {
      reviewStats.total = countRes.data || 0
    }
  } catch (error) {
    console.error('加载评价统计失败:', error)
  }
}

// 预览图片
const previewImage = (url) => {
  // 可以使用Element Plus的图片预览功能
  ElMessage.info('图片预览功能')
}

onMounted(() => {
  loadProductDetail().then(() => {
    if (productDetail.value.id) {
      checkFavoriteStatus()
      loadReviewStats()
      loadReviews()
    }
  })
})
</script>

<style lang="scss" scoped>
.product-detail-page {
  min-height: 100vh;
  background-color: #f5f7fa;

  .container {
    max-width: 1200px;
    margin: 0 auto;
    padding: 20px;
  }

  .breadcrumb {
    margin-bottom: 20px;
  }

  .product-main {
    display: grid;
    grid-template-columns: 1fr 1fr;
    gap: 30px;
    background: white;
    padding: 30px;
    border-radius: 8px;
    margin-bottom: 20px;
  }

  .product-images {
    img {
      width: 100%;
      height: 100%;
      object-fit: contain;
    }
  }

  .product-info {
    .product-name {
      font-size: 24px;
      margin-bottom: 15px;
    }

    .product-meta {
      color: #909399;
      margin-bottom: 20px;
      span {
        margin-right: 20px;
      }
    }

    .price-section {
      padding: 20px;
      background: #fef0f0;
      border-radius: 8px;
      margin-bottom: 20px;

      .current-price {
        font-size: 32px;
        color: #f56c6c;
        font-weight: bold;
        margin-right: 15px;
      }

      .original-price {
        font-size: 18px;
        color: #909399;
        text-decoration: line-through;
        margin-right: 15px;
      }

      .discount {
        background: #f56c6c;
        color: white;
        padding: 2px 8px;
        border-radius: 4px;
        font-size: 14px;
      }
    }

    .stock-info {
      margin-bottom: 30px;
      .low-stock {
        color: #f56c6c;
      }
    }

    .actions {
      display: grid;
      grid-template-columns: 1fr 1fr 1fr;
      gap: 15px;

      .el-button {
        width: 100%;
      }

      .is-favorite {
        color: #f56c6c;
        border-color: #f56c6c;
        background-color: #fef0f0;
        
        &:hover {
          background-color: #fee;
          border-color: #f56c6c;
        }
      }
    }
  }

  .product-detail-section {
    background: white;
    padding: 30px;
    border-radius: 8px;

    .detail-content {
      min-height: 200px;
    }

    .reviews-section {
      .review-stats {
        display: flex;
        gap: 50px;
        padding: 30px;
        background: #f5f7fa;
        border-radius: 8px;
        margin-bottom: 30px;

        .avg-rating {
          text-align: center;
          .rating-value {
            font-size: 48px;
            font-weight: bold;
            color: #f56c6c;
            display: block;
          }
        }
      }

      .review-item {
        padding: 20px;
        border-bottom: 1px solid #ebeef5;

        .review-header {
          display: flex;
          gap: 15px;
          margin-bottom: 15px;

          .review-user-info {
            flex: 1;

            .username {
              font-weight: 500;
              margin-bottom: 5px;
            }

            .review-time {
              color: #909399;
              font-size: 12px;
              margin-left: 10px;
            }
          }
        }

        .review-content {
          margin-bottom: 15px;
          line-height: 1.6;
        }

        .review-images {
          display: flex;
          gap: 10px;
          flex-wrap: wrap;

          img {
            width: 100px;
            height: 100px;
            object-fit: cover;
            border-radius: 4px;
            cursor: pointer;
          }
        }
      }

      .review-pagination {
        margin-top: 20px;
        display: flex;
        justify-content: center;
      }
    }
  }
}
</style>

